<?php 
namespace app\admin\controller;

use think\Db;
use think\Exception;
use app\common\model\notice\NoticeAnnounce;
use app\common\controller\Log;
use app\common\model\admin\AdminUser;
use app\common\controller\Richtext;
use app\common\model\user\UserFeed;

class Notice extends Base
{
	/**
	 * 添加公告
	 * @throws Exception
	 * @return unknown
	 */
	public function addNotice()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			if(!$data['title'])throw new Exception('请输入公告标题');
			if(!$data['content'])throw new Exception('请输入公告内容');
			//添加公告
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['send_admin'] = $this->admin_id;
			NoticeAnnounce::create($data);
			//添加日志
			Log::addLog(1, '添加公告【'.$data['title'].'】');
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加成功');
	}
	
	/**
	 * 公告列表
	 * @return unknown
	 */
	public function noticeList()
	{
		$data = $this->request->post('');
		//初始化查询条件
		$where = ['state' => 1];
		if(!empty($data['title'])) {
			$title = $data['title'];
			$where['title'] = ['like',"%{$title}%"];
		}
		if(!empty($data['times'])){
			$time = [strtotime($data['times'][0]),strtotime($data['times'][1])];
			$where['create_time'] = ['between',$time];
		}
		if(!empty($data['send_admin']))$where['send_admin'] = $data['send_admin'];
		$list = NoticeAnnounce::where($where)->paginate();
		foreach ($list as &$rows) {
			$rows['author'] = AdminUser::get($rows['send_admin'])->admin_real;
			$rows['content'] = Richtext::getStirng($rows['content'], 50);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 删除公告
	 * @return unknown
	 */
	public function deleteNotice()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			if(is_array($data['id'])) {
				$temp = [];
				foreach ($data['id'] as $val) {
					$item = ['state' => 0 ,'update_time' => time(),'id' => $val];
					$temp[] = $item;
				}
				$notice = new NoticeAnnounce();
				$notice -> saveAll($temp);
			} else {
				$notice = NoticeAnnounce::get($data['id']);
				$notice -> save(['state' => 0 ,'update_time' => time()]);
				//添加日志
				Log::addLog(3, "删除公告【{$notice->title}】");
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}
	/**
	 * 反馈列表
	 * @return unknown
	 */
	public function feedList()
	{
		$list = UserFeed::order('id desc')->paginate();
		return jsonSuccess($list);
	}
}